import os
import re


def orign_split_md_by_headers(input_path, output_dir):
    """
    按Markdown标题拆分文件并保存到指定目录
    :param input_path: 输入Markdown文件路径
    :param output_dir: 输出目录
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)

    sections = []
    current_title = None
    level = None
    current_content = []

    with open(input_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 检测标题行
            if line.startswith('#') and len(line) > 1:
                # 解析标题层级
                match = re.match(r'^(#+)\s*(.*)$', line.strip())
                if match:
                    level = str(len(match.group(1)))
                    title_text = match.group(2).strip()

                    # 保存当前章节
                    if current_title:
                        sections.append({
                            'title': current_title,
                            'level': level,
                            'content': current_content
                        })

                    # 开始新章节
                    current_title = title_text
                    level = None
                    current_content = []
                    continue

            # 非标题行内容
            if current_title:
                current_content.append(line)

    # 添加最后一个章节
    if current_title:
        sections.append({
            'title': current_title,
            'level': level,
            'content': current_content
        })
    content = ""
    technology = ""
    tb = False
    # 写入拆分后的文件
    for i, section in enumerate(sections):
        # 生成安全文件名
        safe_title = section['title'].replace('/', '_').replace(' ', '_').replace('*', '_')
        level = section['level']
        # print(f"{safe_title}" + " " + f"{level}")
        # print(f"{i + 1:02d}_{safe_title}")
        # 过滤
        if len(safe_title) > 50:
            continue
        if '目录' in safe_title:
            continue
        # 技术要求
        # if '技术要求' in safe_title or '技术部分' in safe_title:
        if ('技术要求' in safe_title or '技术部分' in safe_title) and '第' in safe_title:
            print(safe_title + " " + level)
        if '技术要求' in safe_title or '技术部分' in safe_title:
            tb = True
            technology += f"{section['title']}"
            # 文本短接着拼接
            if len(''.join(section['content'])) < 5:
                technology += ''.join(section['content'])
                continue
            technology += ''.join(section['content'])
            technology += '#####\n'
            continue
        if tb and level == '1':
            tb = False
        if (tb):
            technology += f"{section['title']}"
            # 文本短接着拼接
            if len(''.join(section['content'])) < 5:
                technology += ''.join(section['content'])
                continue
            technology += ''.join(section['content'])
            technology += '#####\n'
            continue

        # 商务内容
        content += f"{section['title']}"
        # 文本短接着拼接
        if len(''.join(section['content'])) < 5:
            content += ''.join(section['content'])
            continue

        content += ''.join(section['content'])
        content += '#####\n'

        output_path = os.path.join(output_dir, f"{i + 1:02d}_{safe_title}.md")
        """
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(f"# {section['title']}\n\n")
            f.write(''.join(section['content'])) 
        """

    with open("C:\\Users\\user\\Desktop\\918\\解析1\\投标\\商务文件-拆分后.txt", 'w', encoding='utf-8') as f:
        f.write(content)

    with open("C:\\Users\\user\\Desktop\\918\\解析1\\投标\\技术文件-拆分后.txt", 'w', encoding='utf-8') as f:
        f.write(technology)
    return sections


def common_split_md_by_headers(input_path, output_path):
    sections = []
    current_title = None
    level = None
    current_content = []

    with open(input_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 检测标题行
            if line.startswith('#') and len(line) > 1:
                # 解析标题层级
                match = re.match(r'^(#+)\s*(.*)$', line.strip())
                if match:
                    level = str(len(match.group(1)))
                    title_text = match.group(2).strip()

                    # 保存当前章节
                    if current_title:
                        sections.append({
                            'title': current_title,
                            'level': level,
                            'content': current_content
                        })

                    # 开始新章节
                    current_title = title_text
                    level = None
                    current_content = []
                    continue

            # 非标题行内容
            if current_title:
                current_content.append(line)

    # 添加最后一个章节
    if current_title:
        sections.append({
            'title': current_title,
            'level': level,
            'content': current_content
        })
    content = ""
    technology = ""
    tb = False
    # 写入拆分后的文件
    for i, section in enumerate(sections):
        # 生成安全文件名
        safe_title = section['title'].replace('/', '_').replace(' ', '_').replace('*', '_')
        level = section['level']
        # print(f"{safe_title}" + " " + f"{level}")
        # print(f"{i + 1:02d}_{safe_title}")
        # 过滤
        if len(safe_title) > 50:
            continue
        if '目录' in safe_title:
            continue
        # 商务内容
        content += f"{section['title']}"
        # 文本短接着拼接
        if len(''.join(section['content'])) < 5:
            content += ''.join(section['content'])
            continue

        content += ''.join(section['content'])
        content += '#####\n'

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(content)


# 单文件（包含商务+技术）
def single_split_md_by_headers(input_path, output_dir):
    """
    按Markdown标题拆分文件并保存到指定目录
    :param input_path: 输入Markdown文件路径
    :param output_dir: 输出目录
    """
    # 创建输出目录
    # os.makedirs(output_dir, exist_ok=True)

    sections = []
    current_title = None
    level = None
    current_content = []

    with open(input_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 检测标题行
            if line.startswith('#') and len(line) > 1:
                # 解析标题层级
                match = re.match(r'^(#+)\s*(.*)$', line.strip())
                if match:
                    level = str(len(match.group(1)))
                    title_text = match.group(2).strip()

                    # 保存当前章节
                    if current_title:
                        sections.append({
                            'title': current_title,
                            'level': level,
                            'content': current_content
                        })

                    # 开始新章节
                    current_title = title_text
                    level = None
                    current_content = []
                    continue

            # 非标题行内容
            if current_title:
                current_content.append(line)

    # 添加最后一个章节
    if current_title:
        sections.append({
            'title': current_title,
            'level': level,
            'content': current_content
        })
    content = ""
    technology = ""
    tb = False
    # 写入拆分后的文件
    for i, section in enumerate(sections):
        # 生成安全文件名
        safe_title = section['title'].replace('/', '_').replace(' ', '_').replace('*', '_')
        level = section['level']
        # print(f"{safe_title}" + " " + f"{level}")
        # print(f"{i + 1:02d}_{safe_title}")
        # 过滤
        if len(safe_title) > 50:
            continue
        if '目录' in safe_title:
            continue
        # 技术要求
        # if '技术要求' in safe_title or '技术部分' in safe_title:
        if ('技术要求' in safe_title or '技术部分' in safe_title) and '第' in safe_title:
            print(safe_title + " " + level)
        if '技术要求' in safe_title or '技术部分' in safe_title:
            tb = True
            technology += f"{section['title']}"
            # 文本短接着拼接
            if len(''.join(section['content'])) < 5:
                technology += ''.join(section['content'])
                continue
            technology += ''.join(section['content'])
            technology += '#####\n'
            continue
        if tb and level == '1':
            tb = False
        if (tb):
            technology += f"{section['title']}"
            # 文本短接着拼接
            if len(''.join(section['content'])) < 5:
                technology += ''.join(section['content'])
                continue
            technology += ''.join(section['content'])
            technology += '#####\n'
            continue

        # 商务内容
        content += f"{section['title']}"
        # 文本短接着拼接
        if len(''.join(section['content'])) < 5:
            content += ''.join(section['content'])
            continue

        content += ''.join(section['content'])
        content += '#####\n'

        # output_path = os.path.join(output_dir, f"{i + 1:02d}_{safe_title}.md")
        """
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(f"# {section['title']}\n\n")
            f.write(''.join(section['content'])) 
        """

    with open(output_dir + "商务文件-拆分后.txt", 'w', encoding='utf-8') as f:
        f.write(content)

    with open(output_dir + "技术文件-拆分后.txt", 'w', encoding='utf-8') as f:
        f.write(technology)
    return content, technology


# 使用示例
if __name__ == "__main__":
    input_file = 'C:\\Users\\user\\Desktop\\918\\解析1\\投标\\t.md'
    output_file = 'C:\\Users\\user\\Desktop\\918\\output\\file'
    # orign_split_md_by_headers(input_file, output_file)

    single_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析1\\招标\\z.md',
                               'C:\\Users\\user\\Desktop\\918\\解析1\\招标\\')
    single_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析1\\投标\\t.md',
                               'C:\\Users\\user\\Desktop\\918\\解析1\\投标\\')

    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析2\\招标\\商务文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析2\\招标\\商务文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析2\\招标\\富发水解器招标技术规范书.md',
                               'C:\\Users\\user\\Desktop\\918\\解析2\\招标\\技术文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析2\\投标\\水解器采购-天津市欧力诺能源技术有限公司-商务文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析2\\投标\\商务文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析2\\投标\\水解器采购-天津市欧力诺能源技术有限公司-技术文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析2\\投标\\技术文件-拆分后.txt')


    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析3\\招标\\商务文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析3\\招标\\商务文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析3\\招标\\技术文件-浙江华电淳安浪川18.56MW农光互补光伏发电项目液流储能设备采购.md',
                               'C:\\Users\\user\\Desktop\\918\\解析3\\招标\\技术文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析3\\投标\\液流储能设备采购-纬景储能科技有限公司-商务文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析3\\投标\\商务文件-拆分后.txt')
    common_split_md_by_headers('C:\\Users\\user\\Desktop\\918\\解析3\\投标\\液流储能设备采购-纬景储能科技有限公司-技术文件.md',
                               'C:\\Users\\user\\Desktop\\918\\解析3\\投标\\技术文件-拆分后.txt')

